package com.deep.spring.v3;

import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class ExceptionResolver implements HandlerExceptionResolver {

    private static Logger logger = LoggerFactory.getLogger(ExceptionResolver.class);

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception) {
        logger.error("", request.getRequestURL().toString(), exception, request.getParameterMap(), "");

        // 判断是否ajax请求
        if ((request.getHeader("accept").indexOf("application/json") > -1 || (request
                .getHeader("X-Requested-With") != null && request.getHeader(
                "X-Requested-With").indexOf("XMLHttpRequest") > -1))) {
            // 如果是ajax请求，JSON格式返回
            try {
                ResultVo resultVo = new ResultVo(false);
                response.setContentType("application/json;charset=UTF-8");
                PrintWriter writer = response.getWriter();
                // 为安全起见，只有业务异常我们对前端可见，否则统一归为系统异常
                if (exception instanceof BusinessException) {
                    resultVo = new ResultVo(false, ((BusinessException) exception).getErrCode(), ((BusinessException) exception).getErrMsg());
                } else {
                    resultVo = new ResultVo(false, "2342423", "系统异常，请联系管理员");
                }
                writer.write(JSON.toJSONString(resultVo));
                writer.flush();
                writer.close();
            } catch (IOException e) {
                logger.error("", request.getRequestURL().toString(), exception, "aa", request.getParameterMap(), "");
                e.printStackTrace();
            }
        }
        // 对于非ajax请求，我们都统一跳转到500.html页面
        return null;
    }
}